<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-row>
        <a-col :span="6">
          <a-form-model-item label="物料主表配置ID" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cfgid">
            <j-popup
              v-model="model.description"
              field="description"
              org-fields="rec_id,description"
              dest-fields="cfgid,description"
              code="rkjconfig"
              :multi="true"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="送检单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="checkno">
            <a-input v-model="model.checkno" placeholder="请输入送检单号"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
            <a-input v-model="model.ps" placeholder="批次号"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="送检日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="checkdate">
            <j-date placeholder="请选择送检日期" v-model="model.checkdate" style="width: 100%" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="送检次数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="times">
            <a-input-number v-model="model.times" placeholder="请输入送检次数" style="width: 100%" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="报交数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qty">
            <a-input-number v-model="model.qty" placeholder="请输入报交数" style="width: 100%" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="result">
            <j-dict-select-tag type="list" v-model="model.result" dictCode="isOk" placeholder="请选择状态" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="vendor">
            <a-input v-model="model.vendor" placeholder="请输入供应商"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
            <a-input v-model="model.remark" placeholder="备注"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="操作者" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="user">
            <a-input v-model="model.user" placeholder="请输入操作者"></a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-row :gutter="8">
      <!-- 这里是父级节点 -->
      <a-col :span="24">
        <h2>定性项目</h2>
      </a-col>
      <a-col :span="24" style="margin-bottom: 4px;">
        <j-vxe-table
          toolbar
          row-number
          keep-source
          click-select-row
          highlight-current-row
          :radio-config="{highlight: false}"
          :checkbox-config="{highlight: false}"
          :toolbarConfig="toolbarConfig"
          :loading="table1.loading"
          :columns="table1.columns"
          :dataSource="table1.dataSource"
          :pagination="table1.pagination"
          @edit-closed="handleEditClosed"
          @selectRowChange="handleTable1SelectRowChange"
        />
      </a-col>
      <a-col :span="24">
        <h2>定量项目</h2>
      </a-col>
      <a-col :span="24">
        <QuantitativeTable ref="quantitativeTable"></QuantitativeTable>
      </a-col>
    </a-row>
  </j-modal>
</template>

<script>
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import QuantitativeTable from './QuantitativeTable'
import { getAction, postAction } from '@api/manage'

export default {
  name: 'QisMatheadSheetModal',
  props: {
    isSheet: Boolean
  },
  components: {
    QuantitativeTable
  },
  data() {
    return {
      url: {
        getInspectionItems: '/qis/qisMatheadValue/inspectionItems',
        saveRow: '/qis/qisMatheadValue/editQisMatdetailValue',
        verification: '/qis/qisMatheadValue/verificationInspection'
      },
      toolbarConfig: {
        // add 新增按钮；remove 删除按钮；clearSelection 清空选择按钮
        btn: []
      },
      /* 数据源 */
      quantifyDataSource: [],
      expandedRowKeys: [],
      /* table选中keys */
      selectedRowKeys: [],
      // 列表表头
      quantifyColumns: [{
        title: '#',
        dataIndex: '',
        key: 'rowIndex',
        width: 60,
        align: 'center',
        customRender: function(t, r, index) {
          return parseInt(index) + 1
        }
      },
        {
          title: '检验组',
          align: 'center',
          dataIndex: 'orderCode'
        },
        {
          title: '检验描述',
          align: 'center',
          dataIndex: 'ctype'
        },
        {
          title: '工具',
          align: 'center',
          dataIndex: 'orderDate'
        },
        {
          title: '标准值',
          align: 'center',
          dataIndex: 'orderMoney'
        },
        {
          title: '判定',
          align: 'center',
          dataIndex: 'content'
        }],
      table1: {
        // 是否正在加载
        loading: false,
        // 分页器参数
        // 最后选中的行
        lastRow: null,
        // 选择的行
        selectedRows: [],
        // 数据源，控制表格的数据
        dataSource: [],
        // 列配置，控制表格显示的列
        columns: [
          {
            key: 'id',
            title: '序号',
            width: '10%'
          },
          { key: 'checkGroup', title: '检验组', width: '10%' },
          { key: 'checkName', title: '检验描述', width: '30%' },
          { key: 'checkMethod', title: '工具', width: '10%' },
          { key: 'samplingNum', title: '检查数', width: '10%' },
          { key: 'unqualifiedNum', title: '不良数', width: '10%', type: JVXETypes.inputNumber },
          {
            key: 'status',
            title: '判定',
            width: '10%',
            type: JVXETypes.select,
            formatter({ cellValue, row, column }) {
              let foo = ''
              if (row.status === '1') {
                foo = 'OK'
              } else if (row.status === '2') {
                foo = 'N/A'
              } else {
                foo = 'NOK'
              }
              return foo
            },
            options: [
              { title: 'OK', value: '1' },
              { title: 'NOK', value: '0' }
            ]
          }
        ]
      },
      title: '检验单',
      width: '80%',
      visible: false,
      confirmLoading: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      validatorRules: {
        recId: [
          { required: true, message: '请输入主键ID!' }
        ],
        cfgid: [
          { required: true, message: '请输入物料主表配置ID!' }
        ],
        checkno: [
          { required: true, message: '请输入送检单号!' }
        ],
        checkdate: [
          { required: true, message: '请输入送检日期!' }
        ],
        times: [
          { required: true, message: '请输入送检次数!' }
        ],
        user: [
          { required: true, message: '请输入操作者!' }
        ]
      }
    }
  },
  methods: {
    // 单元格编辑完成之后触发的事件
    handleEditClosed(event) {
      let { $table, row, column } = event

      let field = column.property
      let cellValue = row[field]
      // 判断单元格值是否被修改
      if ($table.isUpdateByRow(row, field)) {
        // 校验当前行
        $table.validate(row).then((errMap) => {
          // 校验通过
          if (!errMap) {
            // 【模拟保存】
            let hideLoading = this.$message.loading(`正在保存"${column.title}"`, 0)
            console.log('即时保存数据：', row)
            getAction(this.url.saveRow, row).then(res => {
              if (res.success) {
                this.$message.success(`"${column.title}"保存成功！`)
                // 局部更新单元格为已保存状态
                $table.reloadRow(row, null, field)
              } else {
                this.$message.warn(`"${column.title}"保存失败：` + res.message)
              }
            }).finally(() => {
              hideLoading()
            })
          }
        })
      }
    },
    handleExpand(expanded, record) {
      this.expandedRowKeys = []
      this.innerData = []
      if (expanded === true) {
        this.loading = true
        this.innerData = [
          {
            name: '1',
            value: 5,
            isOK: 'OK'
          }
        ]
        this.expandedRowKeys.push(record.orderCode)
        // getAction(this.url.customerListByMainId, { mainId: record.id }).then((res) => {
        //   if (res.success) {
        //     this.loading = false
        //     this.innerData = res.result.records
        //   }
        // })
      }
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    // 当table1【主表】分页参数变化时触发的事件
    handleTable1PageChange(event) {
      // 重新赋值
      this.table1.pagination.current = event.current
      this.table1.pagination.pageSize = event.pageSize
      // 查询数据
      this.loadTable1Data()
    },
    // table2【子表】当选择的行变化时触发的事件
    handleTable2SelectRowChange(event) {
      this.handleTableSelectRowChange(this.table2, event)
    },
    // table1【主表】当选择的行变化时触发的事件
    handleTable1SelectRowChange(event) {
      this.handleTableSelectRowChange(this.table1, event)
    },
    /** 公共方法：处理表格选中变化事件 */
    handleTableSelectRowChange(table, event) {
      let { row, action, selectedRows, $table } = event
      // 获取最后一个选中的
      let lastSelected = selectedRows[selectedRows.length - 1]
      if (action === 'selected') {
        table.lastRow = row
      } else if (action === 'selected-all') {
        // 取消全选
        if (selectedRows.length === 0) {
          table.lastRow = null
        } else if (!table.lastRow) {
          table.lastRow = lastSelected
        }
      } else if (action === 'unselected' && row === table.lastRow) {
        table.lastRow = lastSelected
      }
      $table.setCurrentRow(table.lastRow)
      table.selectedRows = selectedRows
    },
    handleOk() {
      postAction(this.url.verification, this.model).then((res) => {
        if (res.success) {
          console.log('返回结果')
          this.table1.dataSource = res.result.qualitativeItems
          this.$refs.quantitativeTable.open(res.result.quantitativeItems)
        }
      })
      this.close()
    },
    handleCancel() {
      this.close()
    },
    getInspectionItems() {
      getAction(this.url.getInspectionItems, this.model).then((res) => {
        if (res.success) {
          console.log('返回结果')
          this.table1.dataSource = res.result.qualitativeItems
          this.$refs.quantitativeTable.open(res.result.quantitativeItems)
        }
      })
    },
    open(record) {
      this.model = Object.assign({}, record)
      // 1.根据检验单号请求检验项目
      this.getInspectionItems()
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
    }
  }
}
</script>

<style scoped>

</style>
